<?php

namespace app\model;

use think\Exception;
use think\facade\Db;

class PointsLogModel extends ActionBaseModel
{
    protected $name = 'points_log';


    //积分变动类型
    const MODIFY_TYPE_ADD = 1; //增加积分
    const MODIFY_TYPE_REDUCE = 2; //消耗积分
    //积分变动原因
    const MODIFY_REASON_1 = 1; //注册新用户
    const MODIFY_REASON_2 = 2; //推荐新用户
    const MODIFY_REASON_3 = 3; //兑换积分

    public function pointsModify(array $arrLawUserInfo, array $arrData): bool
    {
        if (empty($arrLawUserInfo) || empty($arrData)) {
            return false;
        }
        $intRemainCount = $arrLawUserInfo['current_points'];
        switch ($arrData['modify_type']) {
            case self::MODIFY_TYPE_ADD:
                $intRemainCount += $arrData['modify_count'];
                break;
            case self::MODIFY_TYPE_REDUCE:
                $intRemainCount -= $arrData['modify_count'];
                break;
            default:
                throw new Exception("积分变动类型有误");
        }
        $arrInsertData = [
            'user_id' => $arrLawUserInfo['id'],
            'modify_type' => $arrData['modify_type'],
            'modify_count' => $arrData['modify_count'],
            'remain_count' => $intRemainCount,
            'modify_reason' => $arrData['modify_reason'],
        ];

        Db::startTrans();
        try {
            //增加日志记录
            $intLow = $this->insert($arrInsertData);
            if (empty($intLow)) {
                throw new Exception('积分变动有误，请重试');
            }

            //剩余积分 同步到 law_user表
            (new LawUserModel())
                ->where([
                    [
                        'id',
                        '=',
                        $arrLawUserInfo['id']
                    ]
                ])
                ->update([
                    'current_points' => $intRemainCount,
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}
